/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { cart, store } from "@mall/api-services"
import * as _ from "lodash"
import { observer } from "mobx-react"
import * as React from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Checkbox from "../components/checkbox"
import CartItem from "./cart-item"
import "./index.scss"
import * as state from "./state"

interface StoreGroupedCartItemsProps extends RouteComponentProps {
  cart: state.Cart;
  storeId: string;
  items: cart.CartItem[];
}

interface StoreGroupedCartItemsState {
  storeInfo: store.Store;
}

@observer
class StoreGroupedCartItems extends React.Component<StoreGroupedCartItemsProps, StoreGroupedCartItemsState> {

  public constructor(props: Readonly<StoreGroupedCartItemsProps>) {
    super(props)

    this.state = {
      storeInfo: store.Store.empty(),
    }
  }

  public componentDidMount(): void {
    store.StoreServiceV1
      .getStore(this.props.storeId)
      .then(storeInfo => this.setState({ storeInfo }))
  }

  public render() {
    const { items, cart, history, storeId } = this.props
    const { storeInfo } = this.state
    return (
      <div className="store-grouped-cart-items-card">
        <Checkbox className="cart-item-checkbox" checked={cart.containsAll(items)} onChange={e => {
          if (e.target.checked) {
            cart.addAll(items)
          } else {
            cart.removeAll(items)
          }
        }}><span className="store-name"
                 onClick={() => history.push(`/stores/${storeId}`)}>{storeInfo.name}</span>
        </Checkbox>
        <div className="cart-items">
          {_.map(items, item => <CartItem key={item.variantId} item={item} cart={cart}/>)}
        </div>
      </div>
    )
  }
}


export default withRouter(StoreGroupedCartItems)
